<?php

namespace jxtebie;

use ShidianUtil\Api\Sms\TemplateSmsResponse;
use ShidianUtil\Net\IHttpClient;
use ShidianUtil\Utils\ConvertUtil;
use think\facade\Config;
use think\facade\Log;
use Throwable;

/**
 * Class Sms
 * @package jxtebie
 */
class Sms
{
    /**
     * @var IHttpClient
     */
    private $httpClient;

    /**
     * ShowApiSms constructor.
     * @param IHttpClient $httpClient
     */
    public function __construct(IHttpClient $httpClient)
    {
        $this->httpClient = $httpClient;
    }

    /**
     * 发送短信
     * @param array $mobiles
     * @param string $content
     * @return TemplateSmsResponse
     */
    public function send(array $mobiles, string $content): TemplateSmsResponse
    {
        $uri = 'https://smsjm.jxtebie.com/sms/submit';

        $config = Config::get('jxtebie', []);

        $post = [];
        $post['spid'] = $config['spid'] ?? '';
        $post['password'] = $config['password'] ?? '';
        $post['ac'] = $config['ac'] ?? '';
        $post['mobiles'] = ConvertUtil::implode($mobiles, ',');
        $post['content'] = $content;

        $response = $this->httpClient->postFORMFormat($uri, [], [], $post);

        $body = $response->getBody()->__toString();

        if ($response->getStatusCode() != 200) {
            Log::error('jxtebie短信发送接口HTTP状态码异常{code}，响应{body}', ['code' => $response->getStatusCode(), 'body' => $body]);
            return new TemplateSmsResponse($response, false, []);
        }

        $data = [];

        try {
            $data = ConvertUtil::xmlDecode($body);

            $result = $data['result'] ?? null;
            if ($result === 0 || $result === '0') {
                return new TemplateSmsResponse($response, true, $data);
            }

            Log::error('jxtebie短信发送接口响应码错误，响应{body}', ['body' => $body]);
            return new TemplateSmsResponse($response, false, $data);
        } catch (Throwable $throwable) {

            Log::error('jxtebie短信发送接口异常，原因{message}', ['message' => $throwable->getMessage()]);
            return new TemplateSmsResponse($response, false, $data);
        }
    }


}
